package com.cddx.logistics.service.impl;


import com.cddx.logistics.domain.pojo.Menu;
import com.cddx.logistics.domain.pojo.Role;
import com.cddx.logistics.mapper.MenuMapper;
import com.cddx.logistics.service.MenuService;
import com.cddx.logistics.service.RoleService;
import com.cddx.logistics.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class MenuServiceImpl implements MenuService {
    @Resource
    private MenuMapper menuMapper;
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;

    @Override
    public List<Menu> getAllMenuTree() {
        return menuMapper.selectMenuTree();
    }

    @Override
    @Transactional
    public List<Menu> getMenuByUserId(Integer userId) {
        List<Role> roles = userService.queryRole(userId);
        if(roles.isEmpty())
            return Collections.emptyList();
        List<Integer> menuIds = roles.stream().map(Role::getRoleId).
                map(roleId -> roleService.queryMenu(roleId)).
                flatMap(List::stream).
                collect(Collectors.toList());
        return menuMapper.selectMenuTree().stream().
                filter(menu -> menuIds.contains(menu.getId())).
                sorted(Comparator.comparing(Menu::getSort)).
                collect(Collectors.toList());
    }

    @Override
    public Menu addMenu(Menu menu) {
        return menuMapper.addMenu(menu) > 0 ? menu : null;
    }

}
